package api

import (
	"gin-demo/models"
	customValidator "gin-demo/pkg/customValidator"
	"gin-demo/pkg/logging"
	"gin-demo/pkg/util"
	"github.com/gin-gonic/gin"
)

// 获取认证的token
func GetAuth(c *gin.Context) {
	var auth models.Auth
	auth.Username = c.PostForm("username")
	auth.Password = c.PostForm("password")

	response := util.NewResponseSuccess()
	// 数据校验
	err := customValidator.Validate(auth)
	if err != nil {
		response.Code = 422
		response.Msg = err.Error()
		util.ResponseSuccess(c, response)
		return
	}

	// 判断用户名和密码是否正确
	ret := models.CheckAuth(auth.Username, auth.Password)
	if ret == 0 {
		response.Code = 422
		response.Msg = "用户名或密码错误"
		logging.Debug(response.Msg)
		util.ResponseSuccess(c, response)
		return
	}

	// 生成token
	token, err := util.GenerateToken(ret)
	if err != nil {
		response.Code = 422
		response.Msg = "生成token失败：" + err.Error()
		logging.Debug(response.Msg)
		util.ResponseSuccess(c, response)
		return
	}

	dataMap := make(map[string]interface{})
	dataMap["token"] = token
	response.Data = dataMap
	util.ResponseSuccess(c, response)
}
